package com.pxmeta.common.config;

import com.alibaba.fastjson.JSONObject;
import com.easemob.im.server.EMProperties;
import com.easemob.im.server.EMService;
import com.pxmeta.common.config.vo.HuanxinReq;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;

/**
 * 环信配置
 */
@Configuration
@Getter
public class HuanxinConfig {
    @Value("${easemob.orgName}")
    private String orgName;
    @Value("${easemob.appName}")
    private String appName;
    @Value("${easemob.clientId}")
    private String clientId;
    @Value("${easemob.clientSecret}")
    private String clientSecret;
    @Value("${easemob.host}")
    private String host;
    @Value("${easemob.baseUrl}")
    private String baseUrl;

    @Value("${easemob.appKey}")
    private String appKey;


    /**
     * 获取环信 token
     * @return
     */
    public JSONObject getToken(){
        String url = baseUrl+"/token";
        RestTemplate restTemplate = new RestTemplate();
        HuanxinReq reqBody = new HuanxinReq();
        reqBody.setClient_secret(clientSecret);
        reqBody.setGrant_type("client_credentials");
        reqBody.setTtl("2592000");
        reqBody.setClient_id(clientId);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<HuanxinReq> entity = new HttpEntity<>(reqBody, headers);

        return restTemplate.postForObject(url, entity, JSONObject.class);
    }

    @Bean
    public EMService service() {
        EMProperties properties = EMProperties.builder()
                .setAppkey(appKey)
                .setClientId(clientId)
                .setClientSecret(clientSecret)
                .build();
        return new EMService(properties);
    }


}
